<?php
/**
 * Created by PhpStorm.
 * User: 刘抱
 * Date: 2018/9/12
 * Time: 10:31
 */

namespace Home\Controller;


use Home\Services\ContractService;
use Home\Services\CrmProjectService;

class ContractBackController extends CommunalController
{
    public function _initialize()
    {
        new LogController();
    }

    //项目合同收款首页
    public function index($excel = null, $project_id = null, $back_status = null, $back_type = null)
    {
        if (empty($excel)) parent::check_permission('CRMH-K', '', '');
        $db_contract_back = M("db_contract_back");
        $db_crm_project = M("db_crm_project");
        $db_contract_invoice = M("db_contract_invoice");
        $db_contract_receipt = M("db_contract_receipt");
        $where['del'] = 1;//未删除
        if (get_permission('CRMH-K', 3, '')) {//个人查看
            $where['_string'] = 'add_uid=' . $this->login_id;
        }
        $res_contract_back_all = $db_contract_back->where($where)->select();//所有的收款计划关联的项目
        $project_ids = array_unique(array_column($res_contract_back_all, 'project_id'));
        $crm_project_array = CrmProjectController::getCrmProjectArray($project_ids);
        $map = array();
        $project_id = isset($project_id) ? $project_id : I('project_id');
        $back_status = isset($back_status) ? $back_status : I('back_status');
        $back_type = isset($back_type) ? $back_type : I('back_type');
        if (!empty($project_id)) $map['project_id'] = $project_id;
        if (!empty($back_status)) $map['back_status'] = $back_status;
        if (!empty($back_type)) $map['type'] = $back_type;
        $res_contract_back = $db_contract_back->where($where)->order('add_date desc')->where($map)->select();
        $res_crm_project = $db_crm_project->where($where)->select();
        foreach ($res_contract_back as $key => $value) {
            foreach ($res_crm_project as $k => $v) {
                if ($value['project_id'] == $v['project_id']) {
                    $res_contract_back[$key]['project_num'] = $v['project_num'];
                    $res_contract_back[$key]['name'] = $v['name'];
                }
            }
        }
        $contract_ids = array_unique(array_column($res_contract_back, 'contract_id'));
        $where_contract['contract_id'] = array('in', $contract_ids);
        $res_contract = M("db_contract")->where($where_contract)->select();

        $back_ids = array_column($res_contract_back, 'back_id');//拿收款计划id去查对应所开的发票
        $back_ids = implode($back_ids, ',');

        $res_contract_invoice = $db_contract_invoice->where($where)->where("back_id in ($back_ids)")->select();
        //把同一收款计划所开的发票列找出来
        $new_invoice = array();
        foreach ($res_contract_invoice as $val) {
            $type = $val['back_id'];
            !isset($new_invoice[$type]) && $new_invoice[$type] = array();
            $new_invoice[$type][] = $val;
        }
        //得到同一收款计划的发票总额
        foreach ($new_invoice as $k => $item) {
            $new_invoice[$k]['make_money_sum'] = array_sum(array_column($item, 'make_money'));
        }

        $res_contract_receipt = $db_contract_receipt->where("back_id in ($back_ids)")->select();//得到阶段的实际收款记录
        //把同一收款计划的收款记录列找出来
        $new_receipt = array();
        foreach ($res_contract_receipt as $val) {
            $type = $val['back_id'];
            !isset($new_receipt[$type]) && $new_receipt[$type] = array();
            $new_receipt[$type][] = $val;
        }
        //得到同一收款计划的回收款总额
        foreach ($new_receipt as $k => $item) {
            $new_receipt[$k]['money'] = array_sum(array_column($item, 'money'));
        }
        foreach ($res_contract_back as $key => $value) {
            //把同一收款计划的发票总额插入到收款计划数组里
            foreach ($new_invoice as $k => $v) {
                if ($value['back_id'] == $k) {
                    $res_contract_back[$key]['make_money_sum'] = $v['make_money_sum'];
                }
            }
            //把统一收款计划的回收款总额插入到收款计划数组里
            foreach ($new_receipt as $m => $n) {
                if ($value['back_id'] == $m) {
                    $res_contract_back[$key]['money'] = $n['money'];
                    $date = array_values(array_filter(array_column($n, 'date')));
                    $count = count($date) - 1;
                    $res_contract_back[$key]['date'] = $date[$count];//拿到最后一次的收款日期
                }
            }
            foreach ($res_contract as $contract) {
                if ($value['contract_id'] == $contract['contract_id']) {
                    $res_contract_back[$key]['contract_number'] = $contract['number'];
                    $res_contract_back[$key]['contract_file_name'] = $contract['file_name'];
                }
            }
        }
        if (isset($excel) && $excel == 1) {
            return $res_contract_back;
            die;
        }
        $res_contract_back = ContractBackController::array_sort($res_contract_back);//按指定字段重新排序
        $new = ContractBackController::array_new($res_contract_back, 'name');
        $count = count($new);
        $Page = new \Think\Page($count, 5);
        $result = array_slice($new, $Page->firstRow, $Page->listRows);
        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('result', $result);
        $this->assign('crm_project_array', $crm_project_array);
        $this->assign('project_id', $project_id);
        $this->assign('back_status', $back_status);
        $this->assign('back_type', $back_type);
        $this->display();
    }

    public function back_excel()
    {
        $project_id = I('project_id');
        $back_status = I('back_status');
        $back_type = I('back_type');
        $res_contract_back = $this->index(1, $project_id, $back_status, $back_type);
        $new = array();
        foreach ($res_contract_back as $k => $value) {
            $new[$k]['name'] = $value['name'];
            $new[$k]['stage'] = $value['stage'];
            $new[$k]['stage_money'] = float_money($value['stage_money']);
            $new[$k]['make_money_sum'] = float_money($value['make_money_sum']);
            $new[$k]['remain'] = float_money($value['stage_money'] - $value['money']);
            $new[$k]['back_status'] = $this->back_status($value['back_status']);
            $new[$k]['type'] = get_contract_back_type($value['type']);
            $new[$k]['money'] = $value['money'];
            $new[$k]['contract_number'] = $value['contract_number'];
            $new[$k]['stage_date'] = $value['stage_date'];
            $new[$k]['date'] = $value['date'];
            $new[$k]['add_uid'] = get_userName($value['add_uid']) . '(' . $value['add_date'] . ')';
        }
        $headArr = array('项目名称', '款项阶段', '计划收款金额', '实收金额', '未收金额', '收款状态', '收款类型', '已开票金额', '合同编号', '计划收款日期', '实际收款日期', '	添加人（日期）');
        $this->downloaddExcel("收款列表", $headArr, $new);
    }

    function back_status($back_status)
    {
        switch ($back_status) {
            case 1:
                $value = '已收';
                break;
            case 2:
                $value = '未收';
                break;
            case 3:
                $value = '部分收';
                break;
            default:
                $value = '';
                break;
        }
        return $value;
    }

    //项目合同收款首页
    public function index_two()
    {
        parent::check_permission('CRMH-K', '', '');
        $db_contract_back = M("db_contract_back");
        $db_crm_project = M("db_crm_project");
        $db_contract_invoice = M("db_contract_invoice");
        $db_contract_receipt = M("db_contract_receipt");
        $where['del'] = 1;//未删除
        if (get_permission('CRMH-K', 3, '')) {//个人查看
            $where['_string'] = 'add_uid=' . $this->login_id;
        }
        $res_contract_back_all = $db_contract_back->where($where)->select();//所有的收款计划关联的项目
        $project_ids = array_unique(array_column($res_contract_back_all, 'project_id'));
        $crm_project_array = CrmProjectController::getCrmProjectArray($project_ids);
        $map = array();
        $project_id = I('project_id');
        if (!empty($project_id)) $map['project_id'] = $project_id;
        $res_contract_back = $db_contract_back->where($where)->order('add_date desc')->where($map)->select();
        $res_crm_project = $db_crm_project->where($where)->select();
        foreach ($res_contract_back as $key => $value) {
            foreach ($res_crm_project as $k => $v) {
                if ($value['project_id'] == $v['project_id']) {
                    $res_contract_back[$key]['project_num'] = $v['project_num'];
                    $res_contract_back[$key]['name'] = $v['name'];
                }
            }
        }
        $back_ids = array_column($res_contract_back, 'back_id');//拿收款计划id去查对应所开的发票
        $back_ids = implode($back_ids, ',');

        $res_contract_invoice = $db_contract_invoice->where($where)->where("back_id in ($back_ids)")->select();
        //把同一收款计划所开的发票列找出来
        $new_invoice = array();
        foreach ($res_contract_invoice as $val) {
            $type = $val['back_id'];
            !isset($new_invoice[$type]) && $new_invoice[$type] = array();
            $new_invoice[$type][] = $val;
        }
        //得到同一收款计划的发票总额
        foreach ($new_invoice as $k => $item) {
            $new_invoice[$k]['make_money_sum'] = array_sum(array_column($item, 'make_money'));
        }

        $res_contract_receipt = $db_contract_receipt->where("back_id in ($back_ids)")->select();//得到阶段的实际收款记录
        //把同一收款计划的收款记录列找出来
        $new_receipt = array();
        foreach ($res_contract_receipt as $val) {
            $type = $val['back_id'];
            !isset($new_receipt[$type]) && $new_receipt[$type] = array();
            $new_receipt[$type][] = $val;
        }
        //得到同一收款计划的回收款总额
        foreach ($new_receipt as $k => $item) {
            $new_receipt[$k]['money'] = array_sum(array_column($item, 'money'));
        }
        foreach ($res_contract_back as $key => $value) {
            //把同一收款计划的发票总额插入到收款计划数组里
            foreach ($new_invoice as $k => $v) {
                if ($value['back_id'] == $k) {
                    $res_contract_back[$key]['make_money_sum'] = $v['make_money_sum'];
                }
            }
            //把统一收款计划的回收款总额插入到收款计划数组里
            foreach ($new_receipt as $m => $n) {
                if ($value['back_id'] == $m) {
                    $res_contract_back[$key]['money'] = $n['money'];
                    $res_contract_back[$key]['date'] = array_pop(array_column($n, 'date'));//拿到最后一次的收款日期
                }
            }
            $back_id = $value['back_id'];
            if ($res_contract_back[$key]['money'] > 0 && $res_contract_back[$key]['money'] == $value['stage_money']) {//更新收款阶段为已收
                $save['back_status'] = 1;

            } elseif ($res_contract_back[$key]['money'] > 0 && $res_contract_back[$key]['money'] < $value['stage_money']) {//更新收款阶段为部分收
                $save['back_status'] = 3;
            } else {//未收
                $save['back_status'] = 2;
            }
            $db_contract_back->where("back_id = $back_id")->save($save);
        }
        $this->redirect('/ContractBack/index');
    }

    //开票页面
    public function add_invoice()
    {
        $back_id = I('back_id');
        $userList = get_userName('');
        $res_back = M("db_contract_back")->where("back_id=$back_id")->find();//获取收款计划信息
        $db_contract_invoice = M("db_contract_invoice");
        $number = $this->get_number();
        $res_contract = ContractController::getContract($res_back['contract_id']);
        $res = array_merge($res_back, $res_contract);
        $res_contract_invoice = $db_contract_invoice->where("back_id=$back_id")->select();
        $ticket_money = array_sum(array_column($res_contract_invoice, 'make_money'));
        //应收总额减去已开发票总额得到剩余应开发票额度
        $res['this_ticket_money'] = $res['stage_money'] - (!empty($ticket_money) ? $ticket_money : 0);
        if (!empty($_POST)) {
            $data = $_POST;
            $data['add_uid'] = $_SESSION['dms_uid'];
            $data['add_date'] = date('Y-m-d H:i:s');
            try {
                M("db_contract_invoice")->add($data);
                $this->success('开票成功', __APP__ . 'ContractBack/index');
                die;
            } catch (\Exception $e) {
                $this->error('开票失败', __APP__ . 'ContractBack/index');
                die;
            }
        }
        $project_id = $res['project_id'];
        $res_crm_project = M("db_crm_project")->field('project_num,name')->where("project_id=$project_id")->find();
        $this->assign('number', $number);
        $this->assign('user_list', $userList);
        $this->assign('res', $res);
        $this->assign('ticket_money', $ticket_money);
        $this->assign('res_crm_project', $res_crm_project);
        $this->display();

    }

    //添加收款记录页
    public function add_receipt()
    {
        $back_id = I('back_id');
        $where['del'] = 1;
        $res_back = M("db_contract_back")->where($where)->where("back_id=$back_id")->find();//获取收款计划信息
        $res_project = CrmProjectController::getCrmProject($res_back['project_id']);
        $res_contract = ContractController::getContract($res_back['contract_id']);
        $res_contract_invoice = M("db_contract_invoice")->where($where)->where("back_id=$back_id")->select();
        $res = array_merge($res_back, $res_project, $res_contract);
        $res['invoice'] = $res_contract_invoice;
        $this->assign('res', $res);
        $this->display();
    }

    //选择发票编号联动查找开票金额和已收款金额
    public function getSumMakeMoneyAndReceiptMoney()
    {
        $invoice_id = I('invoice_id');
        $res_contract_invoice = M("db_contract_invoice")->where("invoice_id=$invoice_id")->find();
        $res_contract_receipt = M("db_contract_receipt")->where("invoice_id=$invoice_id")->select();
        if (!empty($res_contract_receipt)) {
            $receipt_money_list = array_column($res_contract_receipt, 'money');//找出该发票收款列
            $receipt_money_sum = array_sum($receipt_money_list);//求发票收款列的总收款额
        } else {
            $receipt_money_sum = 0;//该发票还未收款
        }
        $money = $res_contract_invoice['make_money'] - $receipt_money_sum;//本次收款金额默认值（发票剩余应收款金额）
        $res = $res_contract_invoice;
        $res['receipt_money_sum'] = $receipt_money_sum;
        $res['money'] = $money;
        echo json_encode($res);
        die;
    }

    //添加收款录入
    public function add_receipt_data()
    {
        $db_contract_receipt = M("db_contract_receipt");
        $db_contract_back = M("db_contract_back");
        $where['back_id'] = $_POST['back_id'];
        $data = $_POST;
        $data['add_uid'] = $_SESSION['dms_uid'];
        $data['add_date'] = date('Y-m-d H:i:s');
        try {
            $db_contract_receipt->add($data);
            $sum_money = $db_contract_receipt->where($where)->sum('money');//阶段实际收款总额
            $sum_stage_money = $db_contract_back->where($where)->sum('stage_money');//收款计划收款额
            if ($sum_money > 0 && $sum_money == $sum_stage_money) {
                $back['back_status'] = '1';//如果收款计划金额与阶段实际收款金额相等 收款状态改为已收
            } else {
                $back['back_status'] = '3';//如果收款计划金额与阶段实际收款金额不等 收款状态改为部分收
            }
            $db_contract_back->where($where)->save($back);
            $this->success('添加收款记录成功', __APP__ . 'ContractBack/index');
        } catch (\Exception $e) {
            $this->error('添加收款记录失败', __APP__ . 'ContractBack/index');
        }
    }

    //发票管理首页
    public function invoice($excel = null, $project_id = null, $contract_id = null, $proposer = null)
    {
        parent::check_permission('CRMF-P', '', '');
        $db_crm_project = M("db_crm_project");
        $db_contract_invoice = M("db_contract_invoice");
        $db_contract = M("db_contract");
        $db_contract_back = M("db_contract_back");
        $where['del'] = 1;
        if (get_permission('CRMF-P', 3, '')) {//个人查看
            $where['_string'] = 'add_uid=' . $this->login_id;
        }
        $project_id_array = $db_contract_invoice->field('project_id')->where($where)->select();
        $project_id_array = array_unique(array_column($project_id_array, 'project_id'));
        $crm_project_array = CrmProjectController::getCrmProjectArray($project_id_array);
        $contract_id_array = $db_contract->field('contract_id,number')->where($where)->group('contract_id')->select();//合同编号
        $proposer_array = $db_contract_invoice->field('proposer')->where($where)->group('proposer')->select();//申请人
        $project_id = isset($project_id) ? $project_id : I('project_id');
        $contract_id = isset($contract_id) ? $contract_id : I('contract_id');
        $proposer = isset($proposer) ? $proposer : I('proposer');
        if (!empty($project_id)) $where['project_id'] = $project_id;
        if (!empty($contract_id)) $where['contract_id'] = $contract_id;
        if (!empty($proposer)) $where['proposer'] = $proposer;
        $res_invoice = $db_contract_invoice->where($where)->order('invoice_id desc')->select();
        $project_ids = implode(',', array_unique(array_column($res_invoice, 'project_id')));//找项目id
        $res_crm_project = $db_crm_project->where($where)->where("project_id in ($project_ids)")->select();//关联项目

        $contract_ids = implode(',', array_unique(array_column($res_invoice, 'contract_id')));//找合同id
        $res_contract = $db_contract->where($where)->where("contract_id in ($contract_ids)")->select();//关联合同

        $back_ids = implode(',', array_unique(array_column($res_invoice, 'back_id')));//找收款id
        $res_contract_back = $db_contract_back->where($where)->where("back_id in ($back_ids)")->select();//关联收款
        foreach ($res_invoice as $key => $value) {
            foreach ($res_crm_project as $k => $v) {
                if ($value['project_id'] == $v['project_id']) {
                    $res_invoice[$key]['name'] = $v['name'];
                    $res_invoice[$key]['project_num'] = $v['project_num'];
                }
            }
            foreach ($res_contract as $k => $v) {
                if ($value['contract_id'] == $v['contract_id']) {
                    $res_invoice[$key]['file_name'] = $v['file_name'];
                    $res_invoice[$key]['file_url'] = $v['file_url'];
                    $res_invoice[$key]['contract_number'] = $v['number'];
                }
            }
            foreach ($res_contract_back as $k => $v) {
                if ($value['back_id'] == $v['back_id']) {
                    $res_invoice[$key]['stage'] = $v['stage'];
                    if ($v['back_status'] != 2) {
                        $res_invoice[$key]['edit'] = 0;//已收款或部分收不能修改发票
                    } else {
                        $res_invoice[$key]['edit'] = 1;//未收款还能修改发票
                    }
                }
            }
        }
        if (isset($excel) && $excel == 1) {
            return $res_invoice;
            die;
        }
        $res_invoice = ContractBackController::array_sort($res_invoice);
        $new = ContractBackController::array_new($res_invoice, 'name');

        $count = count($new);
        $Page = new \Think\Page($count, 5);
        $result = array_slice($new, $Page->firstRow, $Page->listRows);
        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('result', $result);
        $this->assign('crm_project_array', $crm_project_array);
        $this->assign('project_id', $project_id);
        $this->assign('contract_id', $contract_id);
        $this->assign('contract_id_array', $contract_id_array);
        $this->assign('proposer_array', $proposer_array);
        $this->assign('proposer', $proposer);
        $this->display();
    }

    //发票导出Excel
    public function invoice_excel()
    {
        $project_id = I('project_id');
        $proposer = I('proposer');
        $contract_id = I('contract_id');
        $res_invoice = $this->invoice('1', $project_id, $contract_id, $proposer);
        $new = array();
        foreach ($res_invoice as $k => $value) {
            $new[$k]['name'] = $value['name'];
            $new[$k]['no'] = $value['no'];
            $new[$k]['title'] = $value['title'];
            $new[$k]['stage'] = $value['stage'];
            $new[$k]['make_date'] = $value['make_date'];
            $new[$k]['make_money'] = float_money($value['make_money']);
            $new[$k]['contract_number'] = $value['contract_number'];
            $new[$k]['proposer'] = get_userName($value['proposer']);
            $new[$k]['add_uid'] = get_userName($value['add_uid']) . '(' . $value['add_date'] . ')';
        }
        $headArr = array('项目名称', '发票号码', '发票抬头', '关联收款阶段', '开票日期', '开票金额', '合同编号', '申请人', '添加人（日期）');
        $this->downloaddExcel("发票列表", $headArr, $new);
    }

    //发票编辑页
    public function edit_invoice()
    {
        $invoice_id = I('invoice_id');
        $db_contract_invoice = M("db_contract_invoice");
        $db_contract = M("db_contract");
        $db_contract_back = M("db_contract_back");
        $res_contract_invoice = $db_contract_invoice->where("invoice_id=$invoice_id")->find();
        $contract_id = $res_contract_invoice['contract_id'];
        $res_contract = $db_contract->where("contract_id=$contract_id")->find();
        $back_id = $res_contract_invoice['back_id'];
        $project_id = $res_contract_invoice['project_id'];
        $res_contract_back = $db_contract_back->where("back_id=$back_id")->find();
        $res_crm_project = CrmProjectController::getCrmProject($project_id);
        $residue_invoice_money = $db_contract_invoice->where("contract_id=$contract_id and back_id=$back_id and invoice_id<>$invoice_id")->sum('make_money');
        $this->assign('res', $res_contract_invoice);
        $this->assign('res_contract', $res_contract);
        $this->assign('res_contract_back', $res_contract_back);
        $this->assign('res_crm_project', $res_crm_project);
        $this->assign('residue_invoice_money', $residue_invoice_money);
        $userList = get_userName('');
        $this->assign('user_list', $userList);
        if (!empty($_POST)) {
            $data = $_POST;
            try {
                $db_contract_invoice->where("invoice_id=$invoice_id")->save($data);
                $this->success('更新成功', __APP__ . 'ContractBack/invoice');
                die;
            } catch (\Exception $e) {
                $this->error('更新失败', __APP__ . 'ContractBack/invoice');
                die;
            }
        }
        $this->display();
    }

    //发票逻辑删除
    public function del_invoice($invoice_id)
    {
        try {
            $data['del'] = 0;
            M("db_contract_invoice")->where("invoice_id=$invoice_id")->save($data);
            $this->success('删除成功', __APP__ . 'ContractBack/invoice');
        } catch (\Exception $e) {
            $this->error('删除失败', __APP__ . 'ContractBack/invoice');
        }
    }

    //发票列表页添加发票入口
    public function add_invoice_head()
    {
        $number = $this->get_number();
        $db_contract = M("db_contract");
        $db_crm_project = M("db_crm_project");
        $res_contract = $db_contract->where("del=1")->select();
        $project_ids = array_unique(array_column($res_contract, 'project_id'));
        $where_project['project_id'] = array('in', $project_ids);
        $res_crm_project = $db_crm_project->where($where_project)->select();
        /*foreach ($res_contract as $key => $value) {
            foreach ($res_crm_project as $k => $v) {
                if ($value['project_id'] == $v['project_id']) {
                    $res_contract[$key]['name'] = $v['name'];
                }
            }
        }*/
        if (!empty($_POST)) {
            $data = $_POST;
            $contract_id = $_POST['contract_id'];
            $contract_project_id = $db_contract->where("contract_id=$contract_id")->field('project_id')->find();//合同表的项目id
            $contract_project_id = $contract_project_id['project_id'];
            $data['project_id'] = $contract_project_id;
            $data['add_uid'] = $_SESSION['dms_uid'];
            $data['add_date'] = date('Y-m-d H:i:s');
            try {
                M("db_contract_invoice")->add($data);
                $this->success('开票成功', __APP__ . 'ContractBack/invoice');
                die;
            } catch (\Exception $e) {
                $this->error('开票失败', __APP__ . 'ContractBack/invoice');
                die;
            }
        }
        $userList = get_userName('');
        //$this->assign('res_contract', $res_contract);
        $this->assign('number', $number);
        $this->assign('user_list', $userList);
        $this->assign('res_crm_project', $res_crm_project);
        $this->display();
    }

    //添加发票页选择项目关联合同
    public function getContract()
    {
        $project_id = I('project_id');
        $db_contract = M("db_contract");
        $where['del'] = 1;
        $where['project_id'] = $project_id;
        $res_contract = $db_contract->where($where)->select();
        echo json_encode($res_contract);
        die;

    }

    //添加发票页选择关联合同联动关联收款
    public function getContractBack()
    {
        $contract_id = I("contract_id");
        $where['del'] = 1;
        $where['back_status'] = array('neq', 1);
        $res_contract_back = M("db_contract_back")->where("contract_id=$contract_id")->where($where)->select();
        echo json_encode($res_contract_back);
        die;
    }

    //添加发票页选择收款计划联动剩余开票金额
    public function getContractInvoiceMakeMoney()
    {
        $db_contract_invoice = M("db_contract_invoice");
        $db_contract_back = M("db_contract_back");
        $back_id = I('back_id');
        $where['del'] = 1;
        $where['back_id'] = $back_id;
        $sum_make_money = $db_contract_invoice->where($where)->sum('make_money');
        $res_contract_back = $db_contract_back->where($where)->find();
        $money = $res_contract_back['stage_money'] - $sum_make_money;
        $data['money'] = $money;
        $data['sum_make_money'] = !empty($sum_make_money) ? $sum_make_money : 0;
        $data['stage_money'] = $res_contract_back['stage_money'];
        echo json_encode($data);
        die;
    }

    //下一个发票编号
    public function get_number()
    {
        $db_contract_invoice = M("db_contract_invoice");
        $map['number'] = array('notlike', array('FPO%'));
        $contract_number = $db_contract_invoice->field('number')->where($map)->order('number desc')->limit(1)->find();
        $contract_number = !empty($contract_number['number']) ? substr($contract_number['number'], 2) : '000000';
        $number = intval($contract_number);
        $number = 'FP' . str_pad($number + 1, 6, "0", STR_PAD_LEFT);//自增发票编号
        return $number;
    }

    //获取项目的收款记录
    public function get_contract_receipt()
    {
        $project_id = I('project_id');
        $db_contract_receipt = M("db_contract_receipt");
        $db_contract = M("db_contract");
        $db_contract_back = M("db_contract_back");
        $db_contract_invoice = M("db_contract_invoice");
        $where['del'] = array('eq', 1);
        $where['project_id'] = array('eq', $project_id);
        $res_contract_receipt = $db_contract_receipt->where($where)->order('contract_id asc,back_id asc')->select();
        $contract_ids = array_unique(array_column($res_contract_receipt, 'contract_id'));
        $back_ids = array_unique(array_column($res_contract_receipt, 'back_id'));
        $invoice_ids = array_unique(array_column($res_contract_receipt, 'invoice_id'));
        $where_contract['contract_id'] = array('in', $contract_ids);
        $where_back['back_id'] = array('in', $back_ids);
        $where_invoice['receipt_id'] = array('in', $invoice_ids);

        $res_contract = $db_contract->field('contract_id,number')->where($where)->where($where_contract)->select();
        $res_back = $db_contract_back->where($where)->where($where_back)->select();
        $res_invoice = $db_contract_invoice->where($where)->where($where_invoice)->select();

        foreach ($res_contract_receipt as $key => $value) {
            foreach ($res_contract as $contract) {
                if ($value['contract_id'] == $contract['contract_id']) {
                    $res_contract_receipt[$key]['contract_number'] = $contract['number'];
                }
            }
            foreach ($res_back as $back) {
                if ($value['back_id'] == $back['back_id']) {
                    $res_contract_receipt[$key]['back_stage'] = $back['stage'];
                    $res_contract_receipt[$key]['back_stage_money'] = $back['stage_money'];
                    $res_contract_receipt[$key]['back_type'] = $back['type'];
                }
            }
            foreach ($res_invoice as $invoice) {
                if ($value['invoice_id'] == $invoice['invoice_id']) {
                    $res_contract_receipt[$key]['invoice_number'] = $invoice['number'];
                    $res_contract_receipt[$key]['invoice_make_money'] = $invoice['make_money'];
                }
            }
        }
        echo json_encode($res_contract_receipt);
        die;

    }

    /**
     * @param $array
     * @return mixed
     */
    public static function array_sort($array)
    {
        $sort = array(
            'direction' => 'SORT_DESC',//排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
            'direction2' => 'SORT_ASC',//排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
            'field' => 'contract_id',//排序字段
            'field2' => 'stage',//排序字段
        );
        $arrSort = array();
        foreach ($array AS $uniqid => $row) {
            foreach ($row AS $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if ($sort['direction']) {
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arrSort[$sort['field2']], constant($sort['direction2']), $array);
        }
        return $array;
    }

    public static function array_new($array, $field)
    {
        //按项目名相同的重组数组
        $new = array();
        foreach ($array as $val) {
            $type = $val[$field];
            !isset($new[$type]) && $new[$type] = array();
            $new[$type][] = $val;
        }
        return $new;
    }

    //款项统计页
    public function payment_statistics()
    {
        $type = I('type');
        $back_status = I('back_status');
        $invoice_status = I('invoice_status');
        $where_project['del'] = 1;
        if (!empty($type)) $where_project['type'] = $type;

        $field_project = array('project_id', 'project_num', 'name', 'type');//项目表要展示的字段
        $res_project = CrmProjectService::getProjectArray($field_project, $where_project);//项目表数据

        $project_ids = array_column($res_project, 'project_id');//取出项目表ID
        $where_contract['project_id'] = array('in', $project_ids);//合同表条件
        $res_contract = ContractService::getContractArray($field_contract = '*', $where_contract);//合同表数据

        $field_invoice = array('contract_id', 'sum(make_money)' => 'make_money_sum');
        $res_contract_invoice = ContractService::getContractInvoice($field_invoice, null);//已开票数据

        $field_receipt = array('contract_id', 'sum(money)' => 'money_sum');
        $res_contract_receipt = ContractService::getContractReceipt($field_receipt, null);
        $result = ContractService::lastResult($res_contract, $res_project, $res_contract_invoice, $res_contract_receipt, $back_status, $invoice_status);
        $sum = ContractService::lastResultSum($result);//获取合计
        $param = array('type' => $type, 'back_status' => $back_status, 'invoice_status' => $invoice_status);
        $this->assign('param', $param);
        $this->assign('result', $result);
        $this->assign('sum', $sum);
        $this->display();

    }

    /**
     *项目款项统计页的合同详情ajax弹出层
     */
    public function getContractAndBack()
    {
        $contract_id = I('contract_id');
        $where = array();
        if (!empty($contract_id)) $where['contract_id'] = $contract_id;
        $res_contract = ContractService::getContract($field = '*', $where);
        $res_contract_back = ContractService::getContractBackArray($field = '*', $where);
        foreach ($res_contract_back as $key => $value) {
            $res_contract_back[$key]['type_name'] = get_contract_back_type($value['type']);
        }
        $res_contract['add_user'] = get_userName($res_contract['add_uid']);
        $res_contract['stage'] = $res_contract_back;
        echo json_encode($res_contract);
    }

    //款项统计页发票记录
    public function getContractBackAndInvoice()
    {
        $contract_id = I('contract_id');
        $where = array();
        if (!empty($contract_id)) $where['contract_id'] = $contract_id;
        $res_contract_invoice = ContractService::getContractInvoiceArray($field = '*', $where);
        $back_ids = array_unique(array_column($res_contract_invoice, 'back_id'));
        $where['back_id'] = array('in', $back_ids);
        $field_back = array('back_id', 'stage', 'stage_money');
        $res_contract_back = ContractService::getContractBackArray($field_back, $where);
        $result = ContractService::do_invoice($res_contract_back, $res_contract_invoice);
        echo json_encode($result);
    }

    //款项统计页首款记录
    public function getContractBackAndReceipt()
    {
        $contract_id = I('contract_id');
        $where = array();
        if (!empty($contract_id)) $where['contract_id'] = $contract_id;
        $res_contract_receipt = ContractService::getContractReceiptArray($field = '*', $where);
        $back_ids = array_unique(array_column($res_contract_receipt, 'back_id'));
        $where['back_id'] = array('in', $back_ids);
        $field_back = array('back_id', 'stage', 'stage_money');
        $res_contract_back = ContractService::getContractBackArray($field_back, $where);
        $result = ContractService::do_receipt($res_contract_back, $res_contract_receipt);
        echo json_encode($result);
    }

}